package qq2564874169.tuaotuao.fx.orm.jdbc;


import qq2564874169.tuaotuao.fx.orm.MultipleReader;
import qq2564874169.tuaotuao.fx.orm.SqlParam;
import qq2564874169.tuaotuao.fx.orm.Utils;
import qq2564874169.tuaotuao.fx.utils.ExUtil;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class JDBCMultipleReader implements MultipleReader {
    private PreparedStatement statement;
    private boolean first = true;
    private SqlParam param;

    public JDBCMultipleReader(PreparedStatement statement, SqlParam param) {
        this.statement = statement;
        this.param = param;
    }

    @Override
    public <T> List<T> read(Class<T> clazz) {
        try {
            if (first) {
                statement.execute();
                first = false;
            } else if (statement.getMoreResults() == false) {
                throw new RuntimeException("没有更多结果集。");
            }
        } catch (SQLException e) {
            throw ExUtil.toRuntime(e);
        }

        try (ResultSet rs = statement.getResultSet()) {
            List<Map<String,Object>> data = Utils.resultSetToList(rs);
            return param.convert(clazz, data);
        } catch (SQLException e) {
            throw ExUtil.toRuntime(e);
        }
    }

    @Override
    public void close() {
        try {
            statement.close();
            statement = null;
            param = null;
        } catch (SQLException e) {
            throw ExUtil.toRuntime(e);
        }
    }
}
